<?php
/*客户端模型*/
namespace app\api\model;
use plugin\filter;
use plugin\Gateway;
use think\Model;
use think\Session;

class Client extends CommonModel
{
    //当前表名
    protected $table = 'ecs_users';


    public function __construct($args = [])
    {
        parent::__construct($args);
        Gateway::$registerAddress = config('HOME.gatewayregisteraddress');
    }


    /** 客户端id绑定user_id
     * @param $client_id
     * @return array
     */
    public function bind_user($client_id)
    {
        //未登录
        if(empty($this->user_id))
        {
            return ['error'=>2,'msg'=>'未登录'];
        }
        //客户端id
        if(empty($client_id))
        {
            return ['error'=>1,'msg'=>'客户端id错误'];
        }

        //start_register ip
        $user_id = $this->user_id;
        //绑定客户端id
        @Gateway::bindUid($client_id, $this->EncUserid($user_id));
        //设置session
        @Gateway::setSession($client_id,['enc_client_id'=>$this->EncUserid($user_id),'client_id'=>$user_id,'user_name'=>$this->user_name]);

        //响应客户端
        $this->sendOneUser(['type'=>'text','msg'=>'绑定id成功']);


        return ['error'=>0,'msg'=>'success','client_id'=>$this->getUserid(true)];
    }

    /**给指定用户发送信息
     * @param $arr  发送的信息数组     基本格式，包含键值type，msg
     * @param string $user_id     如果该值为空，则默认调用sesson.user_id发送，否则，根据的user_id发送
     * @param string $client_id     如果该值为空，则默认调用sesson.user_id发送，否则，根据客户端id发送
     */
    public function sendOneUser($arr,$user_id = "",$client_id = "")
    {

        //start_register ip
        Gateway::$registerAddress = config('HOME.gatewayregisteraddress');
        $data = json_encode($arr,JSON_UNESCAPED_UNICODE);

        //使用客户端id发送
        if($client_id != "")
        {
            Gateway::sendToClient($client_id,$data);
        }
        //指定某的用户id发送
        elseif(!empty($user_id))
        {
            Gateway::sendToUid($user_id,$data);
        }
        //使用session.user_id发送
        else
        {

            Gateway::sendToUid($this->getUserid(true),$data);
        }

    }

    public function sendAllClient($msg)
    {
        Gateway::sendToAll($msg);
    }

    /**根据用户id获取socket客户端id
     * @param $user_id
     * @return mix
     */
    public function getClientIdByUid($user_id = "")
    {
        $user_id = empty($user_id) ? $this->getUserid(true) : $user_id;
        return Gateway::getClientIdByUid($user_id);
    }

    public function getAllClientSessions()
    {
        return Gateway::getAllClientSessions();
    }

    //获取所有在线的客户端id，返回一个数组
    public function getAllOnLineClientId()
    {
        $session = $this->getAllClientSessions();
        $clientIdArr = [];
        if(!empty($session))
        foreach($session as $k=>$v)
        {
            if(isset($v['enc_client_id']))
            $clientIdArr[] = $v['enc_client_id'];
        }
        return $clientIdArr;
    }

    /**关闭一个客户端
     * @param $client_id
     */
    public function closeClient($client_id)
    {
        Gateway::closeClient($client_id);
    }

    /**聊天内容记录
     * @param $tuser 发送对方sha1_client_id
     * @param $fuser 发送者自己 sha1_client_id
     * @param string $data 发送的内容
     * @param string $type 内容类型，默认为text，如果是图片地址，则是photo
     * @return bool|\mix|mixed|string
     */
    public function chat_log($tuser,$fuser,$data,$type = 'text')
    {
        //判断双方是否在线状态
        $tu_skim = !$this->isOnLine($tuser) ? 0 : 1;
        $fu_skim = !$this->isOnLine($fuser) ? 0 : 1;
        //记录内容
            $msg_id = db('ChatMsg')->insertGetId([
                'content'   => $data,
                'add_time'  => time(),
                'content_type'=> $type
            ]);
            db('ChatMsgUser')->insert([
                'fuser'  => $fuser,
                'tuser'  => $tuser,
                'tu_skim'=> $tu_skim,
                'fu_skim'=> $fu_skim,
                'msg_id' => $msg_id
            ]);
            return $msg_id;
    }

    public function init_msg($data)
    {
        //a标签 新一页跳转
        $patern = '/<a(.+?)>/ius';
        $replacement = '<a ${1} target="blank" >';
        $data = preg_replace($patern,$replacement,$data);

        return $data;
    }



    //用户发送一条消息给用户
    public function send_text($input)
    {
        //允许发送的消息类型
        $text_type = ['text','photo','OffLineText'];

        if(!isset($input) || empty($input['to_client_id']))
        {
            return ['error'=>1,'msg'=>'缺少发送对象'];
        }
        if(!$this->check_login())
        {
            return ['error'=>2,'msg'=>'请先登录'];
        }
        if(!isset($input['type']) || !in_array($input['type'] ,$text_type))
        {
            return ['error'=>1,'msg'=>'未指定消息的类型'];
        }
        $input['msg'] = filter::remove_js($input['msg']);
        if(!isset($input['msg']) || empty($input['msg']))
        {
            return ['error'=>1,'msg'=>'消息不得为空'];
        }

        //判断当前用户发送者是否在线
//        if(!$this->isOnLine())
//        {
//            return ['error'=>4,'msg'=>'已经离线状态，请不要打开多个浏览聊天'];
//        }
        $input['msg'] = $this->init_msg($input['msg']);
        $client_id = $this->getUserid(true);
        //聊天记录
        $msgid = $this->chat_log($input['to_client_id'],$client_id,$input['msg'],$input['type']);
        $time = date('m-d H:i:s',time());
        if($client_id != $input['to_client_id'])
        {
            //客户端给对方发送
            $this->sendOneUser(
                ['type' => $input['type'], 'time'=>$time,'msg' => base64_encode($input['msg']), 'client_id' => $client_id, 'client_name' => $this->nickname, 'msgid' => $msgid, 'is_html_out' => 1, 'is_kf' => $this->isKf]
                , $input['to_client_id']
            );
        }
        //客户端给自己发送
        $this->sendOneUser(
            ['type'=>$input['type'],'time'=>$time,'msg'=>base64_encode($input['msg']),'client_id'=>$client_id,'client_name'=>$this->nickname,'msgid'=>$msgid,'is_html_out'=>1,'is_kf'=>$this->isKf]
        );

        return ['error'=>0,'msg'=>'发送成功'];

    }

    /**判断用户是否在线
     * @param string $user_id 用户enc_client_id,可不填
     * @return bool
     */
    public function isOnLine($user_id = "")
    {
        $user = null;
        $user_id = empty($user_id) ? $this->getUserid(true) : $user_id;
        if(!empty($user_id))
        {
            $OnLineUser = $this->getClientIdByUid($user_id);
            if(!empty($OnLineUser) && isset($OnLineUser[0]) && !empty($OnLineUser[0]))
            {
                $user = $OnLineUser[0];
            }
        }

        return !empty($user);
    }


    public function setClientSession($client_id,$session)
    {
        Gateway::setSession($client_id,$session);
    }

    public function getClientSession($client_id)
    {
        return Gateway::getSession($client_id);
    }

    public function updateClientSession($client_id,$session)
    {
        Gateway::updateSession($client_id,$session);
    }

    public function getSessionByUserid($user_id)
    {
        $client = $this->getClientIdByUid($user_id);
        if(empty($client) || empty($client[0])) return null;
        return $this->getClientSession($client[0]);
    }

}